<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 300px;" class="filter-item" placeholder="组名称" v-model="whereQuery.name"></el-input>
      <el-select clearable style="width: 120px" class="filter-item" v-model="whereQuery.status" placeholder="是否展示" @change="handleFilter">
        <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" align="center" label="组顺序" sortable prop="index">
        <template slot-scope="scope">
          <span>{{scope.row.index}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="300px" header-align="center" label="锁屏组名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" align="center" label="是否展示">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="锁屏组名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="组顺序" prop="index" :rules="[{pattern: /^\d*$/,message: '组顺序只能输入整数值'}]">
          <el-input v-model.number="temp.index"></el-input>
        </el-form-item>
        <el-form-item label="是否展示">
          <el-select class="filter-item" v-model="temp.status" placeholder="请选择">
            <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, insert, deleteById, update } from '@/api/jb'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox } from 'element-ui'

  export default {
    name: 'LockScreenGroup',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          count: true,
          where: {
            name: {
              $regex: '.*'
            },
            status: undefined
          }
        },
        whereQuery: {
          name: undefined,
          status: undefined
        },
        statusTypeOptions: [1, 2],
        temp: {
          _id: undefined,
          name: undefined,
          index: undefined,
          status: undefined
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          name: [{ required: true, message: '组名称不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      statusTypeFilter(status) {
        const statusType = ['展示', '不展示']
        return status > 0 ? statusType[status - 1] : ''
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetch('LockScreenGroup', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.skip = 0
        if (this.whereQuery.name) {
          this.listQuery.where.name = {
            $regex: '.*' + this.whereQuery.name + '.*'
          }
        } else {
          this.listQuery.where.name = undefined
        }
        if (this.whereQuery.status) {
          this.listQuery.where.status = this.whereQuery.status
        } else {
          this.listQuery.where.status = undefined
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          name: undefined,
          status: 2,
          index: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            insert('LockScreenGroup', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            update('LockScreenGroup', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('LockScreenGroup', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      }
    }
  }
</script>
<style scoped>

</style>
